﻿using Core.AdminUI.V2.Controllers.Base;
using Core.AdminUI.V2.Models.User;
using Core.FrameWork.Commons.ApiResult;
using Core.FrameWork.Commons.Extensions;
using Core.FrameWork.Commons.Loging;
using Core.FrameWork.Commons.Mapping;
using Core.FrameWork.Models;
using Core.FrameWork.Models.Enum.User;
using Core.FrameWork.Models.Models.User;
using Core.FrameWork.Models.User;
using Core.FrameWork.Service.User;
using Masuit.Tools.Linq;
using Masuit.Tools.Systems;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace Core.AdminUI.V2.Controllers
{
    /// <summary>
    /// 前台普通用户管理
    /// </summary>
    public class UserSimpleController : BaseController
    {
        /// <summary>
        /// 用户通用服务
        /// </summary>
        private readonly UserService _userService;
        public UserSimpleController(AdminContext adminContext, UserService userService) : base(adminContext)
        {
            _userService = userService;
        }
        #region 视图
        public IActionResult Index()
        {
            ViewBag.Role = CurrentUser.Roles;
            return View();
        }
        public IActionResult Update(string userId = "")
        {
            if (!Guid.TryParse(userId, out var userGId))
            {
                return Redirect("Index");
            }

            var userInfo = _adminContext.UserSimple.Find(userGId);
            if (userInfo == null)
            {
                return Redirect("Index");
            }

            var resp = userInfo.MapTo<UserSimple, RespSimpleUserInfo>();

            return View();
        }
        #endregion

        #region 接口

        /// <summary>
        /// 获取普通用户列表数据
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="userNumber"></param>
        /// <param name="name"></param>
        /// <param name="weChatAccount"></param>
        /// <param name="Sex"></param>
        /// <param name="Enabled"></param>
        /// <param name="beginCTime"></param>
        /// <param name="endCEnd"></param>
        /// <returns></returns>
        [HttpGet]
        [ActionDescription("获取普通用户列表数据", LogResponseData = false)]
        public async Task<PageResult<RespSimpleUser>> GetPageList(int page = 1, int limit = 10, int userNumber = 0, string name = "", string weChatAccount = "", int sex = 2, int enabled = 2, string beginCTime = "", string endCTime = "")
        {
            Expression<Func<UserSimple, bool>> exp = m => true;

            if (userNumber != 0)//用户编号
            {
                exp = exp.And(s => s.UserNumber.Equals(userNumber));
            }
            if (!string.IsNullOrEmpty(name))//用户昵称
            {
                exp = exp.And(s => s.Name.Contains(name));
            }
            if (!string.IsNullOrEmpty(weChatAccount))//微信号
            {
                exp = exp.And(s => s.WeChatAccount.Contains(weChatAccount));
            }
            if (sex != 2)//性别
            {
                exp = exp.And(s => s.Sex.Equals(sex));
            }
            if (enabled != 2)//性别
            {
                if (enabled == 0)
                {
                    exp = exp.And(s => s.Enabled.Equals(false));
                }
                else
                {
                    exp = exp.And(s => s.Enabled.Equals(true));
                }

            }
            if (!string.IsNullOrEmpty(beginCTime))//注册开始时间
            {
                if (DateTime.TryParse(beginCTime, out var beginCTimeD))
                {
                    exp = exp.And(s => s.CreateTime >= beginCTimeD);
                }
            }
            if (!string.IsNullOrEmpty(endCTime))//注册结束时间
            {
                if (DateTime.TryParse(endCTime, out var endCTimeD))
                {
                    exp = exp.And(s => s.CreateTime <= endCTimeD);
                }
            }

            var list = _adminContext.UserSimple.Where(exp).OrderByDescending(m => m.CreateTime)
            .Skip((page - 1) * limit)
            .Take(limit).ToList()
            .ToList();

            int count = _adminContext.UserSimple.Count(exp);

            var resp = list.MapTo<UserSimple, RespSimpleUser>();


            foreach (var item in resp)
            {
                item.VipName = (await _userService.GetUserSimpleLevel(item.MapTo<RespSimpleUser, UserSimple>()))?.VipName ?? "";
            }
            return ApiRespHelp.getApiDataListByPage(resp, count, page, limit);

        }

        /// <summary>
        /// 删除普通用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("删除普通用户", LogResponseData = true)]
        public CommonResult Delete(string Id)
        {
            //权限验证 （超级管理员才可以删除）
            if (!CurrentUser.Roles.Contains("3"))
            {
                return ApiRespHelp.getError(-100, "您没有权限删除用户");
            }


            if (!Guid.TryParse(Id, out var GId))
            {
                return ApiRespHelp.getError(-100, "用户Id 格式错误");
            }

            var userSimpleInfo = _adminContext.UserSimple.Find(GId);

            if (userSimpleInfo == null)
            {
                return ApiRespHelp.getError(100, "未找到用户");
            }

            userSimpleInfo.IsDelete = 1;
            userSimpleInfo.DeleteUser = Guid.Parse(CurrentUser.Id);
            userSimpleInfo.DeleteUserName = CurrentUser.Name;
            userSimpleInfo.DeleteTime = DateTime.Now;

            #region 业务关联删除
            //查询是否有关联的店员
            var userClerk = _adminContext.UserClerk.FirstOrDefault(s => s.OpenId.Equals(userSimpleInfo.OpenId));
            if (userClerk == null)//如果没有关联的店员（删除用户登陆状态记录表）
            {
                var userState = _adminContext.UserState.FirstOrDefault(s => s.OpenId.Equals(userSimpleInfo.OpenId));
                if (userState != null)
                {
                    _adminContext.UserState.Remove(userState);
                }
            }
            else//有关联的店员 （修改登录状态记录表为店员）
            {
                var userState = _adminContext.UserState.FirstOrDefault(s => s.OpenId.Equals(userSimpleInfo.OpenId));
                if (userState != null)
                {
                    userState.Role = UserRole.Clerk.GetDisplay();
                    userState.DefaultRole = UserRole.Clerk;
                }
            }
            #endregion


            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");

        }
        /// <summary>
        /// 批量删除普通用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ActionDescription("批量删除普通用户", LogResponseData = true)]
        public CommonResult BatchDelete(string Ids)
        {
            //权限验证 （超级管理员才可以删除）
            if (!CurrentUser.Roles.Contains("3"))
            {
                return ApiRespHelp.getError(-100, "您没有权限删除用户");
            }

            if (string.IsNullOrEmpty(Ids))
            {
                return ApiRespHelp.getError(-100, "Id不能为空");
            }

            var listIds = Ids.Split(',').Select(s => Guid.Parse(s));

            var userSimpleInfoLists = _adminContext.UserSimple.Where(s => listIds.Contains(s.Id)).ToList();

            if (userSimpleInfoLists.Count == 0)
            {
                return ApiRespHelp.getError(-100, "没有找到删除的用户");
            }

            foreach (var userSimpleInfo in userSimpleInfoLists)
            {
                userSimpleInfo.IsDelete = 1;
                userSimpleInfo.DeleteUser = Guid.Parse(CurrentUser.Id);
                userSimpleInfo.DeleteUserName = CurrentUser.Name;
                userSimpleInfo.DeleteTime = DateTime.Now;
                #region 业务逻辑删除（后期需要性能优化时，再优化）
                //查询是否有关联的店员
                var userClerk = _adminContext.UserClerk.FirstOrDefault(s => s.OpenId.Equals(userSimpleInfo.OpenId));
                if (userClerk == null)//如果没有关联的店员（删除用户登陆状态记录表）
                {
                    var userState = _adminContext.UserState.FirstOrDefault(s => s.OpenId.Equals(userSimpleInfo.OpenId));
                    if (userState != null)
                    {
                        _adminContext.UserState.Remove(userState);
                    }
                }
                else//有关联的店员 （修改登录状态记录表为店员）
                {
                    var userState = _adminContext.UserState.FirstOrDefault(s => s.OpenId.Equals(userSimpleInfo.OpenId));
                    if (userState != null)
                    {
                        userState.Role = UserRole.Clerk.GetDisplay();
                        userState.DefaultRole = UserRole.Clerk;
                    }
                }
                #endregion

            }


            if (_adminContext.SaveChanges() == 0)
            {
                return ApiRespHelp.getError(-100, "操作失败");
            }

            return ApiRespHelp.getSuccess("操作成功");
        }
        #endregion

    }
}

